package com.itx.gatewayx.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.itx.gatewayx.domain.ChatSession;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

/**
 * 聊天会话Mapper接口
 *
 * @author itx
 */
@Mapper
public interface ChatSessionMapper extends BaseMapper<ChatSession> {
    
    /**
     * 获取用户的所有会话
     * 
     * @param userId 用户ID
     * @return 会话列表
     */
    @Select({
        "SELECT s.*, u.username, u.nickname, u.avatar ",
        "FROM chat_session s ",
        "LEFT JOIN user u ON s.target_user_id = u.id ",
        "WHERE s.user_id = #{userId} ",
        "ORDER BY s.update_time DESC"
    })
    List<ChatSession> selectSessionsByUserId(@Param("userId") Long userId);
    
    /**
     * 根据用户ID和目标用户ID查询会话
     * 
     * @param userId 用户ID
     * @param targetUserId 聊天对象用户ID
     * @return 会话
     */
    @Select({
        "SELECT * FROM chat_session ",
        "WHERE user_id = #{userId} AND target_user_id = #{targetUserId} ",
        "LIMIT 1"
    })
    ChatSession selectByUserIdAndTargetUserId(@Param("userId") Long userId, @Param("targetUserId") Long targetUserId);
    
    /**
     * 更新会话最后一条消息
     * 
     * @param sessionId 会话ID
     * @param messageId 消息ID
     * @return 影响行数
     */
    @Update("UPDATE chat_session SET last_message_id = #{messageId}, update_time = NOW() WHERE id = #{sessionId}")
    int updateLastMessage(@Param("sessionId") Long sessionId, @Param("messageId") Long messageId);
} 